/*
 * Project Name demo
 * File Name SocketEventListener
 * Package Name com.huxiaosu.demo.socketio
 * Create Time 2023/1/28
 * Create by name：liujie
 */
package com.huxiaosu.demo.socketio.listener;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.huxiaosu.demo.socketio.dto.ChatMessageDto;
import com.huxiaosu.demo.socketio.service.ChatMsgService;
import com.huxiaosu.demo.socketio.util.SocketCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentMap;

/**
 * Description
 *
 * @ClassName: SocketEventListener
 * @author: liujie
 * @date: 2023/1/28 14:28
 */
@Slf4j
@Component
public class SocketEventListener {
    @Autowired
    private ChatMsgService chatMsgService;
    @OnConnect
    public void onConnect(SocketIOClient client) {
        log.info("socket client connect");
        SocketCache.getInstance().addClient(1,client);

    }

    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        log.info("socket client disconnect");
        ConcurrentMap<Integer, SocketIOClient> all = SocketCache.getInstance().getAll();
        log.info("client count = {}",all.size());
    }

    @OnEvent("test")
    public void testEvent(SocketIOClient client, AckRequest request, ChatMessageDto msg) {
        log.info("test event msg = {}", msg.toString());
        try {
            chatMsgService.saveMsg(msg);
        }catch (Exception e){
            log.info("消息发送失败");
        }
    }
}